package com.butioy.study.jersey.controller;

import cn.hutool.crypto.SecureUtil;
import com.butioy.study.jersey.model.User;
import com.butioy.study.jersey.service.IUserService;
import com.butioy.study.jersey.pojo.Login;
import com.butioy.study.jersey.pojo.Result;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * @author yanglq
 * @since 3.0.0
 */
@Singleton
@Path("user")
public class LoginController {

    private final IUserService userService;

    @Inject
    public LoginController(IUserService userService) {
        this.userService = userService;
    }

    @POST
    @Path("login")
    @Produces(MediaType.APPLICATION_JSON)
    public Result<User> login(@Valid Login login) {
        User user = userService.findByAccount(login.getAccount());
        if (null == user) {
            return Result.fail(1001, "账号或密码错误");
        }

        String encryptedPwd = SecureUtil.sha256(login.getPassword() + user.getPwdSalt());
        if (!encryptedPwd.equals(user.getPwd())) {
            return Result.fail(1001, "账号或密码错误");
        }
        return Result.<User>ok().setData(user);
    }

}
